package com.shanyi.sendmsg.tool;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class IPTool {
    public static String getIP(HttpServletRequest request) throws Exception{

        if (request == null) {
            throw (new Exception("获取到的IP地址为空"));
        }

        String ipStr = request.getHeader("x-forwarded-for");

        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("Proxy-Client-IP");
        }

        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("WL-Proxy-Client-IP");
        }

        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getRemoteAddr();
        }

        String[] arr = ipStr.split(",");
        for (String s : arr) {
            if (!"unknown".equalsIgnoreCase(ipStr)) {
                ipStr = s;
                break;
            }
        }

        return ipStr.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ipStr;
    }
}
